package com.guanghua.brick.html;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guanghua.brick.security.SecurityUtil;
import com.guanghua.brick.util.IConfig;
import com.guanghua.brick.util.StringUtil;
import com.guanghua.brick.util.XmlReader;

abstract public class WebControl implements IControl {
	
	private static Log logger = LogFactory.getLog(WebControl.class);
	
	private String data = null;
	private String[] datas = null;
	private String dataSource = null;
	private boolean commaData = false;
	private String id = "";
	private String name = "";
	private String html = "";
	private String function = null;
	
	private IContent content = null;
	private List<IDepend> depends = null;
	private List<IReplace> replaces = null;

	/**
	 * 继承icontrol必须重载的方法，在该方法中初始化数据源
	 */
	public String build(HttpServletRequest request, HttpServletResponse response, PageContext pageContext) {
		
		//如果配置了权限
		if (function != null) {
			if (!SecurityUtil.functionPermissionValid(function, request)) {
				return "";
			}
		}
		
		//初始化data source
		//如果data有值，就用data中的值，否则看datasource是否有值，有值就解析datasource
		if (this.data == null) {
			if (this.dataSource != null) {
				//调用el解析器解析
				IDataSource ds = getDataSourceParser(pageContext);
				if (ds != null) this.data = ds.parseDataSource(pageContext, dataSource);

				//调用替换器替换
				if (this.data != null && this.replaces != null) {
					Iterator<IReplace> i = this.replaces.iterator(); 
					while (i.hasNext()) {
						this.data = i.next().replace(this.data);
					}
				}
				
			}
		}
		
		//初始化datas的值
		if (datas == null) {
			if (this.data != null) {
				if (this.commaData) {
					datas = StringUtil.stringToStringArray(this.getData());
				} else {
					datas = new String[]{this.getData()};
				}
			} else {
				datas = new String[]{""};
			}
		}
		//构造html string
		return buildHTML(request, response);
	}
	
	/**
	 * 判断选项是否被选中
	 * @param value
	 * @param data
	 * @return
	 */
	protected boolean isSelected(String value) {
		for (int i = 0; i < datas.length; i ++) {
			if (value.equals(datas[i])) {
				return true;
			}
		}
		return false;
	}

	
	/**
	 * 从serlver context中获取data source parser的实现类
	 * @param request
	 * @return
	 */
	public static IDataSource getDataSourceParser(PageContext pageContext) {
		//从servletcontext中获取，如果没有就重新初始化
		String parser = (String)pageContext.getServletContext().getAttribute(IDataSource.DATASOURCE_PARSER);
		if (parser == null) {
			try {
				//读取配置
				XmlReader reader = new XmlReader(pageContext.getServletContext().getRealPath("/WEB-INF/brick.web.xml"), true);
				IConfig[] c = reader.readByTagName("web-datasource-parser");
				if (c != null && c.length != 0 && c[0] != null)
					parser = c[0].getText();
				else 
					parser = "com.guanghua.brick.ui.CommonDataSource";
				
				//放入servletcontext中
				pageContext.getServletContext().setAttribute(IDataSource.DATASOURCE_PARSER, parser);
			} catch (Exception e) {
				logger.error("parse xml /web-inf/brick.web.xml to find datasource parser error, use default", e);
				parser = "com.guanghua.brick.ui.CommonDataSource";
			}
		}
		
		try {
			IDataSource ds = (IDataSource)Class.forName(parser).newInstance();
			return ds;
		} catch (InstantiationException e) {
			logger.error("class init error:"+parser, e);
		} catch (IllegalAccessException e) {
			logger.error("class access error:"+parser, e);
		} catch (ClassNotFoundException e) {
			logger.error("not found class:"+parser, e);
		}
		
		return null;
	}
	
	/**
	 * 控件必须重载的buildHTML方法
	 * @param request
	 * @param response
	 * @return
	 */
	abstract public String buildHTML(HttpServletRequest request, HttpServletResponse response);

	public IContent getContent() {
		return content;
	}

	public void setContent(IContent content) {
		this.content = content;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public List<IDepend> getDepends() {
		return depends;
	}

	public void setDepends(List<IDepend> depends) {
		this.depends = depends;
	}

	public String getHtml() {
		return html;
	}

	public void setHtml(String html) {
		this.html = html;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDataSource() {
		return dataSource;
	}

	public void setDataSource(String dataSource) {
		this.dataSource = dataSource;
	}
	
	public List<IReplace> getReplaces() {
		return replaces;
	}

	public void setReplaces(List<IReplace> replaces) {
		this.replaces = replaces;
	}

	public String getFunction() {
		return function;
	}

	public void setFunction(String function) {
		this.function = function;
	}
	
	public boolean isCommaData() {
		return commaData;
	}

	public void setCommaData(boolean commaData) {
		this.commaData = commaData;
	}

	public String[] getDatas() {
		return datas;
	}

	public void setDatas(String[] datas) {
		this.datas = datas;
	}
}
